package cn.gcjxsc.filter;

import cn.gcjxsc.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author pumbaa
 * @since 1.0
 */
@Component
public class MerchantPreFilter implements Filter {
    @Autowired
    protected AuthService authService;

//    @Value("${rw.merchant.merchant.check-auth}")
    private boolean checkAuth = false;

    private static final String EMPLOY_PREFIX = "employ_";
    private static final String EMPLOY_EXPIRE_PREFIX = "employ_expire_";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (checkAuth) {
            String sessid = request.getParameter("PHPSESSID");
            if (StringUtils.isEmpty(sessid)) {
                sessid = AuthUtil.getPHPSessionId(request);
            }
            if (StringUtils.isEmpty(sessid)) {
                AuthUtil.ajaxResponse(response);
            }
            Long expireTime = authService.getExpireTime(EMPLOY_EXPIRE_PREFIX + sessid);
            Integer employId = authService.getAuthIden(EMPLOY_PREFIX + sessid);
            if (null == employId) {
                AuthUtil.ajaxResponse(response);
            }
            else {
                //session过期
                if (null != expireTime && expireTime < System.currentTimeMillis() /1000) {
                    authService.expireKeys(EMPLOY_EXPIRE_PREFIX + sessid, EMPLOY_PREFIX + sessid);
                    AuthUtil.ajaxResponse(response);
                }
                if (null == expireTime) {
                    expireTime = System.currentTimeMillis()/1000;
                }
                authService.updateExpireTime(EMPLOY_EXPIRE_PREFIX + sessid, expireTime + 3600);

                HttpSession session = request.getSession();
                session.setAttribute("employId", employId);
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
        else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
